package com.googlecode.openrtp.grizzly.session;

import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.googlecode.openrtp.grizzly.RtpSessionFactory;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import com.googlecode.openrtp.spi.Names;
import com.googlecode.openrtp.spi.RtpSession;
import com.googlecode.openrtp.spi.RtpSessionManager;
import com.googlecode.openrtp.spi.SessionKeys;

/**
 *
 * @author jocke
 */
@Singleton
public class DefaultRtpSessionManager implements RtpSessionManager {

    private static final Logger LOG = Logger.getLogger(DefaultRtpSessionManager.class.getName());
    private final int rtpBandwidth;
    private final int rtcpBandwidthFraction;
    private final RtpSessionContext sessionContext;
    private final RtpSessionFactory sessionFactory;

    @Inject
    public DefaultRtpSessionManager(
            @Named(Names.RTP_BANDWIDTH) int rtpBandwidth,
            @Named(Names.RTCP_BANDWIDTH_FRACTION) int rtcpBandwidthFraction,
            RtpSessionContext sessionContext,
            RtpSessionFactory sessionFactory) {
        this.rtpBandwidth = rtpBandwidth;
        this.rtcpBandwidthFraction = rtcpBandwidthFraction;
        this.sessionContext = sessionContext;
        this.sessionFactory = sessionFactory;
    }

    @Override
    public RtpSession lookup(Long ssrc) {
        Objects.requireNonNull(ssrc);
        return sessionContext.getBySsrc(ssrc);
    }

    @Override
    public RtpSession lookup(String cname) {
        Objects.requireNonNull(cname);
        return sessionContext.getByCname(cname);
    }

    public int getRtpBandwidth() {
        return rtpBandwidth;
    }

    public int getRtcpBandwidthFraction() {
        return rtcpBandwidthFraction;
    }

    @Override
    public void register(RtpSession session, Long ssrc) {
        LOG.log(Level.INFO, "Will add session {0}", ssrc);
        Objects.requireNonNull(session);
        Objects.requireNonNull(ssrc);
        sessionContext.putBySsrc(ssrc, session);
    }

    @Override
    public void register(RtpSession session, String cname) {
        Objects.requireNonNull(session);
        Objects.requireNonNull(session.lookup(SessionKeys.SSRC));
        sessionContext.putByCname(cname, session);
    }

    @Override
    public RtpSession create(Long ssrc) {
        RtpSession session = sessionFactory.create(ssrc);
        register(session, ssrc);
        return session;
    }
}
